# coding=utf-8
import hashlib
import re
import time
from os import environ

import xmltodict
from flask import Blueprint, jsonify, request, make_response

from config import logger
from utils import fetch_movie
from utils.fetch_music import fetch_music

wxRouter = Blueprint('wxRouter', import_name=__name__, url_prefix='/wx')
WX_TOKEN = environ.get('WX_TOKEN', '')

COMMAND_RE = r'/.+-.+'
COMMAND_FUNC = {
    u'电影': fetch_movie.do_fetch,
    u'音乐': fetch_music
}


def __handle_text(xml_data):
    Content = xml_data['Content']  # 文本消息内容
    ToUserName = xml_data['ToUserName']  # 开发者微信号
    FromUserName = xml_data['FromUserName']  # 发送方帐号（一个OpenID）
    CreateTime = xml_data['CreateTime']  # 消息创建时间 （整型）
    MsgId = xml_data['MsgId']  # 消息id，64位整型
    answer = None
    info = u'没有资源'
    if Content.startswith('/') and (isinstance(Content, unicode) or isinstance(Content, str)):
        if not re.match(COMMAND_RE, Content):
            info = u'命令无效‍,请发送类似命令: /电影-降魔传 、/音乐-不要说话陈奕迅"️'
        else:
            temp = Content.split('/')[1].split('-')
            command = temp[0]
            arg = temp[1]
            func = COMMAND_FUNC.get(command)
            if func:
                answer = func(arg)
            else:
                info = u'奴家不知道这个({})命令'.format(command)
    else:
        info = u'还没有支持这个'
    if answer:
        data = {
            'ToUserName': FromUserName,
            'FromUserName': ToUserName,
            'CreateTime': int(time.time()),
            'MsgType': 'news',
            'ArticleCount': len(answer),
            'Articles': {
                'item': answer
            }
        }
    else:
        data = {
            'ToUserName': FromUserName,
            'FromUserName': ToUserName,
            'CreateTime': int(time.time()),
            'MsgType': 'text',
            'Content': info
        }
    xml = xmltodict.unparse({"xml": data})
    response = make_response(xml)
    response.headers['Content-type'] = 'application/xml'
    return response


def __handle_pic(xml_data):
    PicUrl = xml_data['PicUrl']  # 图片链接（由系统生成）
    ToUserName = xml_data['ToUserName']  # 开发者微信号
    FromUserName = xml_data['FromUserName']  # 发送方帐号（一个OpenID）
    CreateTime = xml_data['CreateTime']  # 消息创建时间 （整型）
    MsgId = xml_data['MsgId']  # 消息id，64位整型
    # response
    content = u'天气好晴朗，处处花儿香'
    data = {
        'ToUserName': FromUserName,
        'FromUserName': ToUserName,
        'CreateTime': int(time.time()),
        'MsgType': 'text',
        'Content': content
    }
    xml = xmltodict.unparse({"xml": data})
    response = make_response(xml)
    response.headers['Content-type'] = 'application/xml'
    return response


__handles = {
    'text': __handle_text,
    'image': __handle_pic
}


@wxRouter.route('', methods=['GET'])
def hello():
    try:
        data = request.args
        signature = data.get('signature')
        timestamp = data.get('timestamp')
        nonce = data.get('nonce')
        echo_str = data.get('echostr')
        token = WX_TOKEN
        lt = [token, timestamp, nonce]
        lt.sort()
        sha1 = hashlib.sha1()
        map(sha1.update, lt)
        hashcode = sha1.hexdigest()
        logger.info("hashcode: {}, signature: {}".format(hashcode, signature))
        if hashcode == signature:
            return echo_str
        else:
            return jsonify(msg='token invalid!'), 401
    except Exception as e:
        return jsonify(msg=e.message.__str__()), 500


@wxRouter.route('', methods=['POST'])
def get_post():
    try:
        data = request.data
        if 'xml' in request.mimetype:
            xml_data = xmltodict.parse(data)['xml']
            MsgType = xml_data['MsgType']
            func = __handles.get(MsgType)
            if func:
                resp = func(xml_data)
                return resp
            logger.info('un support type:{}'.format(MsgType))
        return 'success'
    except Exception as e:
        logger.error(e, exc_info=True)
        return 'success'
